package com.woniuxy.auth.controller;

import com.woniuxy.auth.entity.User;
import com.woniuxy.commons.bean.ResponseResult;

import com.woniuxy.commons.enums.ResponseStatus;
import com.woniuxy.commons.util.JWTUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author: 15489  <br/>
 * Date: 2022/3/29:15:41  <br/>
 * Description:
 */
@RestController
@RequestMapping("/auth")
public class AuthController {
    @Resource
    private RedisTemplate<String,Object>redisTemplate;

    //    1.认证
    @PostMapping("/login")
    public ResponseResult<Object>login(@RequestBody User user, HttpServletResponse response){
//            通过账号作为查询条件去数据库查询用户信息判断账号密码

//    假设账号密码没问题
//        1：生成 token refreshtoken
        String token= JWTUtil.generateToken(user.getUname());
        String refreshToken= UUID.randomUUID().toString();

//        2 以 refreshToken 作为key token 账号作为value放到redis 中
        Map<String,Object> map=new HashMap<>();
        map.put("token",token);
        map.put("uname",user.getUname());
        redisTemplate.opsForHash().putAll(refreshToken,map);

//        设置过期时间
        redisTemplate.expire(refreshToken,30, TimeUnit.DAYS);

//       3 设置响应头 返回token refreshToken
        response.setHeader("authorization",token);
        response.setHeader("refreshtoken",refreshToken);
//        暴露 头
        response.setHeader("Access-Control-Expose-Headers","authorization,refreshtoken");

//        4：响应结果
        ResponseResult<Object> result=new ResponseResult<>();
        result.setCode(200);
        result.setMessage("success");
        result.setStatus(ResponseStatus.LOGIN_SUCCESS);

        return  result;
    }

    //    2.授权
    @GetMapping("/hasPrerms/{uname}/{perms}")
    public  ResponseResult<Object> hasPerms(@PathVariable("uname") String uname, @PathVariable("perms") String perms){
        ResponseResult<Object> result=new ResponseResult<>();

//        通过账号作为查询条件 查询初当前用户的所有权限
//        假设查询到了
        List<String>  allPerms= Arrays.asList("goods::find","goods::update","goods::add");
        for(String str: allPerms){
            if(perms.equals(str)){
//                有权限
                result.setCode(200);
                result.setMessage("有权限 ");
                result.setStatus(ResponseStatus.SUCCESS);
//                返回结果
                return result;
            }
        }
//        没有权限
        result.setCode(500);
        result.setMessage("没有权限 ");
        result.setStatus(ResponseStatus.FAIL);
        return result;

    }

}
